<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Medium\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\Medium\Action\Dashboard\Traits\MediumTrait;
use MoChat\App\Medium\Action\Dashboard\Traits\RequestTrait;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 查询 - 列表.
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;
    use RequestTrait;
    use MediumTrait;

    /**
     * @Inject
     * @var MediumContract
     */
    protected $mediumService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/medium/store", methods="POST")
     */
    public function handle(): array
    {
        $user = user();

        // 参数验证
        $params = $this->request->all();
        $this->validated($params, 'store');
        $content = $this->request->input('content');
        $content['size'] = $this->size($content);
        $data = [
            'type' => $this->request->input('type'),
            'is_sync' => (int) $this->request->input('isSync', 2),
            'content' => Json::encode($content),
            'corp_id' => $user['corpId'],
            'medium_group_id' => $this->request->input('mediumGroupId'),
            'user_id' => $user['id'],
            'user_name' => $user['name'],
            'created_at' => date('Y-m-d H:i:s'),
        ];

        // 数据操作
        Db::beginTransaction();
        try {
            // 添加单条
            $this->mediumService->createMedium($data);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '素材添加失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required|integer|min:1|bail',
            'content' => 'required|array',
            'mediumGroupId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => '类型 必传',
            'content.required' => '素材内容 必传',
            'mediumGroupId.required' => '素材分组id 必传',
        ];
    }
}
